local json = require "cjson"
local md5 = require "md5"

local M = {}

function M:load()
    local steam_id = self:get_steam_id()
    local ok, user_map = FILE_D:read_common_data("user", "user", steam_id)
    if not ok then
        return false
    end

    local ok, item_map = FILE_D:read_common_data("item", "item", steam_id)
    if not ok then
        return false
    end

    if #user_map > 0 and #(user_map[1])>0 then
        local checksum = FILE_D:salt_md5(user_map[1])
        if checksum ~= user_map[2] then
            spdlog.error("M:load", string.format("user:load steam_id:%s user checksum error old:%s now:%s",steam_id, user_map[2], checksum))
            return false
        end

        local ok, user_dbase = pcall(json.decode, user_map[1])
        if not ok then
            return false
        end

        ---! 玩家基本数据
        self:set_entire_dbase(user_dbase)
        self:set_checksum(checksum)

    ---! 其他操作
    ----todo:
    end

    if #item_map > 0  and #(item_map[1])>0 then
        local checksum = FILE_D:salt_md5(item_map[1])
        if checksum ~= item_map[2] then
            spdlog.error("M:load", string.format("item:load steam_id:%s item checksum error old:%s now:%s",steam_id, item_map[2], checksum))
            return false
        end
        local ok, item_dbase = pcall(json.decode, item_map)
        if not ok then
            return false
        end

        ---! 还原道具数据
        item_dbase:set_checksum(checksum)
        ITEM_D:restore_item_dbase(self, item_dbase)


    end

    ---! 加载成功
    return true
end

function M:save()
    --local user_id = self:get_id()
    local steam_id = self:get_steam_id()

    ---! 保存道具数据
    local item_dbase = ITEM_D:query_item_dbase(self)
    if item_dbase then
        --print("M:save item_dbase",item_dbase)
        --dump(item_dbase)
        local str = json.encode(item_dbase)
        local checksum = FILE_D:salt_md5(str)
        local old_checksum = item_dbase:get_checksum()
        printf("M:save item old_checksum:%s new_checksum:%s", old_checksum, checksum)
        if checksum ~= old_checksum then
            item_dbase:set_checksum(checksum)
            FILE_D:write_common_data("item", "item", steam_id, "", str, checksum)
        end
    end

    ---! 保存基本数据
    local user_dbase = self:query_entire_dbase()
    if user_dbase then
        local str = json.encode(user_dbase)
        local checksum = FILE_D:salt_md5(str)
        local old_checksum = self:get_checksum()
        printf("M:save user old_checksum:%s new_checksum:%s", old_checksum, checksum)
        if checksum ~= old_checksum then
            self:set_checksum(checksum)
            FILE_D:write_common_data("user", "user", steam_id, "", str, checksum)
        end
    end
end

function M:saveUserinfo()
end

F_CHAR_SAVE = M
